<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>期权双卖策略分析工具</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
        }
        h2 {
            color: #34495e;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
            margin-top: 30px;
        }
        .input-section {
            background-color: #ecf0f1;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .input-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .input-group {
            display: flex;
            flex-direction: column;
        }
        label {
            font-weight: bold;
            color: #555;
            margin-bottom: 5px;
            font-size: 14px;
        }
        input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        input:focus {
            outline: none;
            border-color: #3498db;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            margin: 10px 5px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #2980b9;
        }
        .results-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .results-table th {
            background-color: #3498db;
            color: white;
            padding: 12px;
            text-align: left;
            font-weight: bold;
        }
        .results-table td {
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        .results-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .results-table tr:hover {
            background-color: #e3f2fd;
        }
        .metric-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        .metric-card {
            background-color: #f8f9fa;
            border-left: 4px solid #3498db;
            padding: 15px;
            border-radius: 5px;
        }
        .metric-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }
        .metric-value {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
        .chart-container {
            margin: 30px 0;
            height: 400px;
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
        }
        .highlight {
            background-color: #2ecc71 !important;
            color: white;
        }
        .warning {
            color: #e74c3c;
            font-weight: bold;
        }
        #savedStrategies {
            margin-top: 20px;
            max-height: 300px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📊 期权双卖策略分析工具</h1>
        
        <div class="input-section">
            <h2>基础数据输入</h2>
            <div class="input-grid">
                <div class="input-group">
                    <label>标的现价</label>
                    <input type="number" id="spotPrice" value="4.00" step="0.01">
                </div>
                <div class="input-group">
                    <label>到期天数</label>
                    <input type="number" id="daysToExpiry" value="30" step="1">
                </div>
                <div class="input-group">
                    <label>无风险利率(%)</label>
                    <input type="number" id="riskFreeRate" value="2.5" step="0.1">
                </div>
            </div>
        </div>

        <div class="input-section">
            <h2>期权组合输入</h2>
            <div id="strategyInputs">
                <div class="strategy-input" data-index="0">
                    <h3 style="color: #7f8c8d;">策略组合 1</h3>
                    <div class="input-grid">
                        <div class="input-group">
                            <label>认购执行价</label>
                            <input type="number" class="call-strike" value="4.2" step="0.1">
                        </div>
                        <div class="input-group">
                            <label>认购权利金</label>
                            <input type="number" class="call-premium" value="0.08" step="0.01">
                        </div>
                        <div class="input-group">
                            <label>认购Delta</label>
                            <input type="number" class="call-delta" value="-0.3" step="0.01">
                        </div>
                        <div class="input-group">
                            <label>认购IV(%)</label>
                            <input type="number" class="call-iv" value="18" step="0.1">
                        </div>
                    </div>
                    <div class="input-grid">
                        <div class="input-group">
                            <label>认沽执行价</label>
                            <input type="number" class="put-strike" value="3.8" step="0.1">
                        </div>
                        <div class="input-group">
                            <label>认沽权利金</label>
                            <input type="number" class="put-premium" value="0.07" step="0.01">
                        </div>
                        <div class="input-group">
                            <label>认沽Delta</label>
                            <input type="number" class="put-delta" value="0.25" step="0.01">
                        </div>
                        <div class="input-group">
                            <label>认沽IV(%)</label>
                            <input type="number" class="put-iv" value="20" step="0.1">
                        </div>
                    </div>
                </div>
            </div>
            
            <button onclick="addStrategy()">➕ 添加策略组合</button>
            <button onclick="calculateAll()">📈 计算分析</button>
            <button onclick="exportToCSV()">💾 导出CSV</button>
        </div>

        <div id="results" style="display: none;">
            <h2>分析结果</h2>
            
            <div class="metric-cards" id="summaryMetrics">
                <!-- 动态生成汇总指标 -->
            </div>

            <h3>策略对比表</h3>
            <table class="results-table">
                <thead>
                    <tr>
                        <th>策略组合</th>
                        <th>执行价组合</th>
                        <th>权利金合计</th>
                        <th>保证金</th>
                        <th>组合胜率</th>
                        <th>静态收益率</th>
                        <th>年化收益率</th>
                        <th>期望收益率</th>
                        <th>风险调整收益</th>
                        <th>综合得分</th>
                    </tr>
                </thead>
                <tbody id="resultsTableBody">
                    <!-- 动态生成结果 -->
                </tbody>
            </table>

            <div class="chart-container">
                <canvas id="analysisChart"></canvas>
            </div>

            <h3>最优策略建议</h3>
            <div id="recommendations" class="metric-cards">
                <!-- 动态生成建议 -->
            </div>
        </div>

        <div id="savedStrategies">
            <h3>历史记录</h3>
            <div id="historyList"></div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <script>
        let strategyCount = 1;
        let analysisChart = null;
        let analysisResults = [];

        function addStrategy() {
            const container = document.getElementById('strategyInputs');
            const newStrategy = document.createElement('div');
            newStrategy.className = 'strategy-input';
            newStrategy.dataset.index = strategyCount;
            
            newStrategy.innerHTML = `
                <h3 style="color: #7f8c8d;">策略组合 ${strategyCount + 1}</h3>
                <div class="input-grid">
                    <div class="input-group">
                        <label>认购执行价</label>
                        <input type="number" class="call-strike" value="${parseFloat(document.getElementById('spotPrice').value) + 0.2}" step="0.1">
                    </div>
                    <div class="input-group">
                        <label>认购权利金</label>
                        <input type="number" class="call-premium" value="0.06" step="0.01">
                    </div>
                    <div class="input-group">
                        <label>认购Delta</label>
                        <input type="number" class="call-delta" value="-0.25" step="0.01">
                    </div>
                    <div class="input-group">
                        <label>认购IV(%)</label>
                        <input type="number" class="call-iv" value="18" step="0.1">
                    </div>
                </div>
                <div class="input-grid">
                    <div class="input-group">
                        <label>认沽执行价</label>
                        <input type="number" class="put-strike" value="${parseFloat(document.getElementById('spotPrice').value) - 0.2}" step="0.1">
                    </div>
                    <div class="input-group">
                        <label>认沽权利金</label>
                        <input type="number" class="put-premium" value="0.05" step="0.01">
                    </div>
                    <div class="input-group">
                        <label>认沽Delta</label>
                        <input type="number" class="put-delta" value="0.2" step="0.01">
                    </div>
                    <div class="input-group">
                        <label>认沽IV(%)</label>
                        <input type="number" class="put-iv" value="20" step="0.1">
                    </div>
                </div>
                <button onclick="removeStrategy(${strategyCount})" style="background-color: #e74c3c;">删除此组合</button>
            `;
            
            container.appendChild(newStrategy);
            strategyCount++;
        }

        function removeStrategy(index) {
            const strategy = document.querySelector(`[data-index="${index}"]`);
            if (strategy) {
                strategy.remove();
            }
        }

        function calculateMargin(spotPrice, callStrike, putStrike, callPremium, putPremium) {
            // 认购保证金
            const callOTM = Math.max(0, callStrike - spotPrice);
            const callMargin = callPremium + Math.max(spotPrice * 0.12 - callOTM, spotPrice * 0.07);
            
            // 认沽保证金
            const putOTM = Math.max(0, spotPrice - putStrike);
            const putMargin = Math.min(
                putPremium + Math.max(spotPrice * 0.12 - putOTM, putStrike * 0.07),
                putStrike
            );
            
            // 组合保证金
            return Math.max(callMargin, putMargin) + Math.min(callPremium, putPremium);
        }

        function calculateAll() {
            const spotPrice = parseFloat(document.getElementById('spotPrice').value);
            const daysToExpiry = parseFloat(document.getElementById('daysToExpiry').value);
            const strategies = document.querySelectorAll('.strategy-input');
            
            analysisResults = [];
            
            strategies.forEach((strategy, index) => {
                const callStrike = parseFloat(strategy.querySelector('.call-strike').value);
                const callPremium = parseFloat(strategy.querySelector('.call-premium').value);
                const callDelta = parseFloat(strategy.querySelector('.call-delta').value);
                const callIV = parseFloat(strategy.querySelector('.call-iv').value);
                
                const putStrike = parseFloat(strategy.querySelector('.put-strike').value);
                const putPremium = parseFloat(strategy.querySelector('.put-premium').value);
                const putDelta = parseFloat(strategy.querySelector('.put-delta').value);
                const putIV = parseFloat(strategy.querySelector('.put-iv').value);
                
                // 计算保证金
                const margin = calculateMargin(spotPrice, callStrike, putStrike, callPremium, putPremium);
                
                // 计算胜率
                const winRate = (1 - Math.abs(callDelta)) * (1 - Math.abs(putDelta));
                
                // 计算收益率
                const totalPremium = callPremium + putPremium;
                const staticReturn = (totalPremium / margin) * 100;
                const annualizedReturn = staticReturn * (365 / daysToExpiry);
                
                // 计算期望收益率
                const expectedLoss = staticReturn * 1.5; // 经验值
                const expectedReturn = winRate * staticReturn - (1 - winRate) * expectedLoss;
                
                // 计算风险调整收益
                const strikeWidth = callStrike - putStrike;
                const riskAdjustedReturn = staticReturn / (strikeWidth / spotPrice);
                
                // 计算综合得分
                const avgIV = (callIV + putIV) / 2;
                const timeEfficiency = totalPremium / Math.sqrt(daysToExpiry);
                
                analysisResults.push({
                    index: index + 1,
                    callStrike,
                    putStrike,
                    totalPremium,
                    margin,
                    winRate,
                    staticReturn,
                    annualizedReturn,
                    expectedReturn,
                    riskAdjustedReturn,
                    avgIV,
                    timeEfficiency,
                    strikeWidth
                });
            });
            
            // 标准化并计算综合得分
            normalizeAndScore();
            
            // 显示结果
            displayResults();
            
            // 保存到历史记录
            saveToHistory();
        }

        function normalizeAndScore() {
            // 获取最大最小值用于标准化
            const expectedReturns = analysisResults.map(r => r.expectedReturn);
            const winRates = analysisResults.map(r => r.winRate);
            const timeEfficiencies = analysisResults.map(r => r.timeEfficiency);
            const riskAdjustedReturns = analysisResults.map(r => r.riskAdjustedReturn);
            
            const normalize = (value, min, max) => {
                if (max === min) return 50;
                return ((value - min) / (max - min)) * 100;
            };
            
            analysisResults.forEach(result => {
                const normalizedExpectedReturn = normalize(
                    result.expectedReturn,
                    Math.min(...expectedReturns),
                    Math.max(...expectedReturns)
                );
                
                const normalizedWinRate = normalize(
                    result.winRate,
                    Math.min(...winRates),
                    Math.max(...winRates)
                );
                
                const normalizedTimeEfficiency = normalize(
                    result.timeEfficiency,
                    Math.min(...timeEfficiencies),
                    Math.max(...timeEfficiencies)
                );
                
                const normalizedRiskAdjusted = normalize(
                    result.riskAdjustedReturn,
                    Math.min(...riskAdjustedReturns),
                    Math.max(...riskAdjustedReturns)
                );
                
                // 综合得分（可调整权重）
                result.score = (
                    normalizedExpectedReturn * 0.4 +
                    normalizedWinRate * 0.3 +
                    normalizedTimeEfficiency * 0.2 +
                    normalizedRiskAdjusted * 0.1
                ).toFixed(1);
            });
            
            // 按得分排序
            analysisResults.sort((a, b) => b.score - a.score);
        }

        function displayResults() {
            document.getElementById('results').style.display = 'block';
            
            // 显示汇总指标
            displaySummaryMetrics();
            
            // 填充表格
            const tbody = document.getElementById('resultsTableBody');
            tbody.innerHTML = '';
            
            analysisResults.forEach((result, index) => {
                const row = tbody.insertRow();
                if (index === 0) row.className = 'highlight';
                
                row.innerHTML = `
                    <td>策略 ${result.index}</td>
                    <td>C${result.callStrike}/P${result.putStrike}</td>
                    <td>${result.totalPremium.toFixed(3)}</td>
                    <td>${result.margin.toFixed(2)}</td>
                    <td>${(result.winRate * 100).toFixed(1)}%</td>
                    <td>${result.staticReturn.toFixed(2)}%</td>
                    <td>${result.annualizedReturn.toFixed(1)}%</td>
                    <td class="${result.expectedReturn < 0 ? 'warning' : ''}">${result.expectedReturn.toFixed(2)}%</td>
                    <td>${result.riskAdjustedReturn.toFixed(2)}</td>
                    <td><strong>${result.score}</strong></td>
                `;
            });
            
            // 绘制图表
            drawChart();
            
            // 显示建议
            displayRecommendations();
        }

        function displaySummaryMetrics() {
            const container = document.getElementById('summaryMetrics');
            const bestStrategy = analysisResults[0];
            
            container.innerHTML = `
                <div class="metric-card">
                    <div class="metric-label">最优策略</div>
                    <div class="metric-value">策略 ${bestStrategy.index}</div>
                </div>
                <div class="metric-card">
                    <div class="metric-label">最高期望收益</div>
                    <div class="metric-value">${bestStrategy.expectedReturn.toFixed(2)}%</div>
                </div>
                <div class="metric-card">
                    <div class="metric-label">平均胜率</div>
                    <div class="metric-value">${(analysisResults.reduce((sum, r) => sum + r.winRate, 0) / analysisResults.length * 100).toFixed(1)}%</div>
                </div>
                <div class="metric-card">
                    <div class="metric-label">平均年化收益</div>
                    <div class="metric-value">${(analysisResults.reduce((sum, r) => sum + r.annualizedReturn, 0) / analysisResults.length).toFixed(1)}%</div>
                </div>
            `;
        }

        function drawChart() {
            const ctx = document.getElementById('analysisChart').getContext('2d');
            
            if (analysisChart) {
                analysisChart.destroy();
            }
            
            analysisChart = new Chart(ctx, {
                type: 'scatter',
                data: {
                    datasets: [{
                        label: '策略分布',
                        data: analysisResults.map(r => ({
                            x: r.winRate * 100,
                            y: r.expectedReturn,
                            label: `策略${r.index}`
                        })),
                        backgroundColor: analysisResults.map((r, i) => 
                            i === 0 ? 'rgba(46, 204, 113, 0.8)' : 'rgba(52, 152, 219, 0.6)'
                        ),
                        borderColor: analysisResults.map((r, i) => 
                            i === 0 ? 'rgba(46, 204, 113, 1)' : 'rgba(52, 152, 219, 1)'
                        ),
                        pointRadius: analysisResults.map((r, i) => i === 0 ? 10 : 6),
                        pointHoverRadius: 12
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: '胜率 vs 期望收益率分布',
                            font: { size: 16 }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const result = analysisResults[context.dataIndex];
                                    return [
                                        `策略 ${result.index}`,
                                        `胜率: ${context.parsed.x.toFixed(1)}%`,
                                        `期望收益: ${context.parsed.y.toFixed(2)}%`,
                                        `综合得分: ${result.score}`
                                    ];
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '胜率 (%)'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '期望收益率 (%)'
                            }
                        }
                    }
                }
            });
        }

        function displayRecommendations() {
            const container = document.getElementById('recommendations');
            const best = analysisResults[0];
            const spotPrice = parseFloat(document.getElementById('spotPrice').value);
            
            let riskLevel = '中等';
            let ivEnvironment = '正常';
            
            if (best.strikeWidth / spotPrice > 0.15) riskLevel = '保守';
            else if (best.strikeWidth / spotPrice < 0.08) riskLevel = '激进';
            
            if (best.avgIV > 25) ivEnvironment = '高波动';
            else if (best.avgIV < 15) ivEnvironment = '低波动';
            
            container.innerHTML = `
                <div class="metric-card" style="grid-column: span 2;">
                    <div class="metric-label">推荐策略</div>
                    <div class="metric-value">策略 ${best.index}: C${best.callStrike}/P${best.putStrike}</div>
                    <p style="margin-top: 10px;">
                        该策略具有${(best.winRate * 100).toFixed(1)}%的胜率，
                        预期月收益率${best.expectedReturn.toFixed(2)}%，
                        风险级别为${riskLevel}。
                    </p>
                </div>
                <div class="metric-card">
                    <div class="metric-label">市场环境</div>
                    <div class="metric-value">${ivEnvironment}</div>
                    <p style="margin-top: 10px; font-size: 14px;">
                        当前隐含波动率${best.avgIV.toFixed(1)}%
                    </p>
                </div>
                <div class="metric-card">
                    <div class="metric-label">建议仓位</div>
                    <div class="metric-value">${(100 / Math.max(5, 100 / best.expectedReturn)).toFixed(0)}%</div>
                    <p style="margin-top: 10px; font-size: 14px;">
                        基于Kelly公式的保守估计
                    </p>
                </div>
            `;
        }

        function exportToCSV() {
            if (analysisResults.length === 0) {
                alert('请先进行计算分析！');
                return;
            }
            
            let csv = '策略,认购执行价,认沽执行价,权利金合计,保证金,胜率,静态收益率,年化收益率,期望收益率,综合得分\n';
            
            analysisResults.forEach(r => {
                csv += `${r.index},${r.callStrike},${r.putStrike},${r.totalPremium.toFixed(3)},${r.margin.toFixed(2)},${(r.winRate * 100).toFixed(1)}%,${r.staticReturn.toFixed(2)}%,${r.annualizedReturn.toFixed(1)}%,${r.expectedReturn.toFixed(2)}%,${r.score}\n`;
            });
            
            const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `期权双卖策略分析_${new Date().toISOString().slice(0, 10)}.csv`;
            link.click();
        }

        function saveToHistory() {
            const history = JSON.parse(localStorage.getItem('optionStraddleHistory') || '[]');
            const timestamp = new Date().toLocaleString('zh-CN');
            
            if (analysisResults.length > 0) {
                const best = analysisResults[0];
                history.unshift({
                    timestamp,
                    spotPrice: document.getElementById('spotPrice').value,
                    bestStrategy: `C${best.callStrike}/P${best.putStrike}`,
                    expectedReturn: best.expectedReturn.toFixed(2),
                    score: best.score
                });
                
                // 只保留最近20条记录
                if (history.length > 20) history.pop();
                
                localStorage.setItem('optionStraddleHistory', JSON.stringify(history));
                displayHistory();
            }
        }

        function displayHistory() {
            const history = JSON.parse(localStorage.getItem('optionStraddleHistory') || '[]');
            const container = document.getElementById('historyList');
            
            if (history.length === 0) {
                container.innerHTML = '<p style="color: #999;">暂无历史记录</p>';
                return;
            }
            
            let html = '<table class="results-table" style="font-size: 14px;"><thead><tr><th>时间</th><th>标的价格</th><th>最优策略</th><th>期望收益</th><th>得分</th></tr></thead><tbody>';
            
            history.slice(0, 5).forEach(record => {
                html += `<tr>
                    <td>${record.timestamp}</td>
                    <td>${record.spotPrice}</td>
                    <td>${record.bestStrategy}</td>
                    <td>${record.expectedReturn}%</td>
                    <td>${record.score}</td>
                </tr>`;
            });
            
            html += '</tbody></table>';
            container.innerHTML = html;
        }

        // 页面加载时显示历史记录
        window.onload = function() {
            displayHistory();
        };
    </script>
</body>
</html>